//
//  ST_TIANGlobalMethod.swift
//  btvideo
//
//  Created by Jason on 2021/11/1.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import NIMSDK
import DeviceKit
import SwiftyUserDefaults


/// 新需求，男的使用老的，女的使用新的真人认证弹窗样式
func ToastDetectFaceTips(vcCreater:(()->UIViewController)?){
    
    if Defaults[.isPanda]{
        
        let alert = BTVerticalAlertViewController.createDetectFaceForTalkAlert(title: "通过真人认证才能使用", content: "完成了真人头像认证后就可以\n发送消息，发布特质，发布评论。", confirmStr: "立即认证", cancelStr: "取消",viewHeight:372)
        
        
        alert.confirm_closure = {
            
            TIANFaceLogicHandle(controller: TopmostViewController())
        }
        
        GlobalPresent(toController: alert)
        
        return
    }
    
    if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
        
        GlobalPresent(toController: ST_FaceTipsFullScreenController())
        
        return
    }
    
    if let vc = vcCreater?(){
        
        GlobalPresent(toController: vc)
        
    }
    
}


func PlayFeedBack(){
    
    let canNotFeedBackDevices:[Device] = [.iPhone6Plus,.iPhone6,.iPhoneSE]
    
    if canNotFeedBackDevices.contains(Device.current) {
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        
    }else{
        AudioServicesPlaySystemSound(1519)
    }
    
//    print("次数------")
    
}
/**
 喜欢或者忽略操作
 Parameter
 likeAction 喜欢或者不喜欢
 isReceive 收到的喜欢
 
 response status = 1 , 请求成功
 */
func PairsLikeAction(info:ST_MatchUserInfo,likeAction:Bool = true,isReceive:Bool = false,fromVC:UIViewController?,propId:String? = nil,responseClosure:@escaping ((_ status:Int,_ error:String?,_ matched:(()->())?)->())) {
    
    
    
    PlayFeedBack()
    
    if likeAction && isReceive == false && ST_BTLaunchController.shared.AI_CARD_SIDE_NUMBER < 1 && FETCH_MEMBER_STATUS() != .subscribe{
        
        
        ST_MaidWayManager.shared.source = .卡片耗尽
        
        let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.无线喜欢次数)

        vc.overCurrentContext = true

        GlobalPresent(toController: vc)
        
        responseClosure(0,nil,nil)
        
        return
    }
    
    
    var api = PH.likeActionV50Api
     
    if !likeAction{
        api = PH.dislikeActionV50Api
    }
     
    var param = ["target_accid":info.accid]
    
    var reducePropNumberBlock:(()->())?
    
//    接受喜欢
    if isReceive{
        param.updateValue("2", forKey: "option_type")
    }
//    普通喜欢
    else{
        param.updateValue("1", forKey: "option_type")
        

    //    使用道具喜欢
        if let pid = propId , likeAction{
            
            
            param.updateValue(pid, forKey: "props_id")
            
            reducePropNumberBlock = {
             
            }
        }
    }
    
    
    
    
    JVrequest(api,parameters: param, success: { (json) in
        
        
        print("喜欢😍 json:",json)
        
        reducePropNumberBlock?()
        
        if likeAction && isReceive == false{
            
            ST_BTLaunchController.shared.AI_CARD_SIDE_NUMBER -= 1
            
            fromVC?.toast_multi_line(text: "喜欢成功！互相喜欢成为好友！")
        }
        
        if likeAction == false{
            ST_BTUserInfoManager.shared.delete_match(accid: info.accid)
        }
        
        NotificationCenter.default.post(name: Notification.Name.showedSomeOne, object: nil, userInfo: ["fromController":fromVC ?? 0,"id":info.accid,"isThumbUp":likeAction])
        
        if let coin = json["data"]["sweet_currency"].float{
            
            ST_BTUserInfoManager.shared.modify_sweet_coin(value: coin)
        }
        
        
        
        if json["data"]["mutual_like"].boolValue{
                
            responseClosure(1,nil,{
                
                ST_BTUserInfoManager.shared.receive_match(json: json["data"])
                
                ST_BTBootController.shared.matchSuccess(info: info)
            })
            
            let props = json["data"]["props"]
            
            let integral = props["integral"].doubleValue
            
            if integral > 0{
                
                ST_BTUserInfoManager.shared.increase_income(value: integral, msgSendDate: Date())
                
                let message = NIMMessage()
                
                let attach = ST_Custom255AttachmentModel()
                
                attach.type = 2
                
                attach.goodsId = props["id"].stringValue
                attach.title = "\(props["name"].stringValue)喜欢了你"
                attach.subTitle = String(format: "+%.2f\(Defaults[.PandaStr])", integral)
                attach.imageUrl = props["image"].stringValue
                        
                let customObj = NIMCustomObject()
                
                customObj.attachment = attach
                
                message.messageObject = customObj
                
                NIMSDK.shared().conversationManager.save(message, for: NIMSession.init(info.accid, type: NIMSessionType.P2P)) { (error) in

                    print("插入消息错误 ---:",error ?? "-无--")
                    
                }
                
            }
            
        }else{
            
            responseClosure(1,nil,nil)
        }
        
    }) { (code, err) in
        
        if code == 10001{
            
            ST_MaidWayManager.shared.source = .卡片耗尽

            let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.无线喜欢次数)

            vc.overCurrentContext = true

            GlobalPresent(toController: vc)
            
            return
        }
        
        responseClosure(0,err,nil)
    }
    
}



/**
 关注 取消关注 某人 error为空 请求成功
 */
func FollowBehavior(info:ST_MatchUserInfo,followed:Bool,fromCards:Bool = false,responseClosure:@escaping ((_ matchSuccess:Bool,_ error:String?)->())){
    
    PlayFeedBack()
    
    let api = followed ? PH.un_attentionSomebadyApi : PH.attentionSomebadyApi
    
    var param = ["target_accid":info.accid]
    
    if fromCards{
        param.updateValue("2", forKey: "access_type")
    }
    
    JVrequest(api,parameters: param, success: { (json) in
        
//        喜欢成功
        if !followed{
            
            NotificationCenter.default.post(name: Notification.Name.liked_somebody, object: nil, userInfo: ["id":info.accid])
            
        }
        
        if json["data"]["mutual_like"].boolValue{
                                
            ST_BTUserInfoManager.shared.receive_match(json: json["data"])
            
            ST_BTBootController.shared.matchSuccess(info: info)
            
            responseClosure(true, nil)
            
        }else{
            
            if followed{
                
                ST_BTUserInfoManager.shared.delete_match(accid: info.accid)
                
            }
            
            responseClosure(false, nil)
        }
        
    }) { (code, err) in
        
        responseClosure(false, err)
    }
    
}

/**
 关注 取消关注 某人 error为空 请求成功
 */
func FollowBehavior(info:ST_MatchUserInfo,followControl:UIControl,responseClosure:@escaping ((_ matchSuccess:Bool,_ error:String?)->())){
    
    followControl.isUserInteractionEnabled = false
    
    FollowBehavior(info: info, followed: followControl.isSelected) { (f, err) in

        if err == nil{
            followControl.isSelected = !followControl.isSelected
        }
        
        
        followControl.isUserInteractionEnabled = true
        
        responseClosure(f, err)
    }
    
}


/**
 不感兴趣 某人
 */
func IgnoreBehavior(userId:String,responseClosure:@escaping ((_ success:Bool,_ error:String)->())){
    
    JVrequest(PH.unlikePersonApi,parameters:["target_accid":userId],success: { (json) in
        
        print("【忽略】某个用户",json)
    
        responseClosure(true, "")
            
            
    }) { (code, err) in
        
        responseClosure(false, err)
    }
    
}


/**
 全局【喜欢】【匹配成功】
 */

extension UIViewController {
    
    /**
     全局喜欢不喜欢 调用
     isLike :当前操作 【喜欢】 或者 【不喜欢】
     loveSquare:喜欢首页，收到的喜欢 使用 true
     */
    func likeBehavior(info:ST_MatchUserInfo,isLike:Bool = true,loveSquare:Bool = false,loveWay:ST_LoveWay = .recommend,peculiarity:String = ""){
        
        self.likeBehavior(info: info, isLike: isLike, loveSquare: loveSquare,loveWay:loveWay,peculiarity:peculiarity) { s in
            
        }
        
    }
    
    /**
     全局喜欢不喜欢 调用
     isLike :当前操作 【喜欢】 或者 【不喜欢】
     loveSquare:喜欢首页，收到的喜欢 使用 true
     responseClosure [matchSuccess 为真 不关闭界面]
     revertClosure 重置操作
     */
    func likeBehavior(info:ST_MatchUserInfo,isLike:Bool = true,loveSquare:Bool = false,refreshloveIndex:Bool = true,loveWay:ST_LoveWay = .recommend,peculiarity:String = "",responseClosure:@escaping ((_ matchSuccess:Bool)->()),revertClosure:@escaping (()->())){
        
        
            
            var api = PH.likePersonApi
            
            var param = ["target_accid":info.accid,"send_way":loveWay.rawValue] as [String : Any]
            
            if loveSquare{
                
                if isLike{
                    
                    api = PH.receiveLikePersonApi
                    
                }else{
                    
                    api = PH.refundPersonApi
                }
                
            }else{
                if !isLike{
                    api = PH.unlikePersonApi
                }else if !peculiarity.isEmpty{
                    param.updateValue(peculiarity, forKey: "feature_id")
                }
            }
            
            PlayFeedBack()
        
            JVrequest(api,parameters:param,success: { (json) in
                
                print("【喜欢or忽略】api:",api,"某个用户",json)
                
                if isLike{
                    
                    
                    if json["data"]["mutual_like"].boolValue{
                        
                        ST_BTUserInfoManager.shared.receive_match(json: json["data"])
                        
                        ST_BTBootController.shared.matchSuccess(info: info)
                        
                        responseClosure(true)
                        
                    }else{
                        
                        responseClosure(false)
                        
                    }
                    
                }else{
                    
                    responseClosure(false)
                    
                }
                
                if refreshloveIndex{
                    NotificationCenter.default.post(name: Notification.Name.refresh_pairs_love_controller, object: nil)
                }
                
                
                
                
            }) { (code, err) in
                
                revertClosure()
                
                self.hidden_indeterminate_h_u_d()
                
                if 10001 == code{
                    
                    ST_MaidWayManager.shared.source = .卡片耗尽
                    
                    let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.无线喜欢次数)

                    vc.overCurrentContext = true

                    GlobalPresent(toController: vc)
                    
                    
                }else if 400 == code{
                    
                    let attrString = NSMutableAttributedString(string: "提示")
                 
                    let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
                    attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                    
                    let attrString1 = NSMutableAttributedString(string: err)
                    
                    let paragh = NSMutableParagraphStyle()
                    paragh.alignment = .center
                    
                    let attr1: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1),.paragraphStyle:paragh]
                    
                    attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
                    
                    
                    let alert = ST_BTAlertViewController.init(title: attrString, message: attrString1, imageName: "首页_img_喜欢提示", confirmText: "确定", cancelText: "")

                    alert.overCurrentContext = true
                    
                    alert.over_current_context_alpha = "0.4"

                    alert.root_view_height = 270
                    
                    alert.root_view_width = 250
                    
                    GlobalPresent(toController: alert)
                    
                }else{
                    
                    print("当前 返回喜欢不喜欢 错误信息：",err)
                    
                    ToastHud(text: err, view: self.view)
                }
            
            
            
        }
    }
    
    /**
     全局喜欢不喜欢 调用
     isLike :当前操作 【喜欢】 或者 【不喜欢】
     loveSquare:喜欢首页，收到的喜欢 使用 true
     responseClosure [matchSuccess 为真 不关闭界面]
     */
    func likeBehavior(info:ST_MatchUserInfo,isLike:Bool = true,loveSquare:Bool = false,refreshloveIndex:Bool = true,loveWay:ST_LoveWay = .recommend,peculiarity:String = "",responseClosure:@escaping ((_ matchSuccess:Bool)->())){
        
        
        self.likeBehavior(info: info, isLike: isLike, loveSquare: loveSquare,loveWay:loveWay,peculiarity:peculiarity, responseClosure: { (f) in
            responseClosure(f)
        }) {
            
        }
        
    }
    
    func matchSuccess(info:ST_MatchUserInfo){
        
        matchSuccess(accid: info.accid, avatar: info.avatar, nickname: info.nickname)
        
    }
    
    
    func matchSuccess(accid:String,avatar:String,nickname:String)  {
        
        let m = ST_MediaInfoModel()
        m.video_member_accid = accid
        m.video_member_avatar = avatar
        m.video_member_nickname = nickname
        
//        self.matchSuccess(model: m)
                
        BINP.update_base_info(remoteInfo: ST_BTUserInfoFromRemote(accid: accid, avatar: avatar, userName: nickname))
        
        
        
        let pair = ST_BTPairSuccessController()
        
        pair.someone = m
        
      
        
        pair.chatClosure = { someone in
            
            
            let vc = ST_PrivateChatViewController()
            
            vc.sessionID = accid
            
            vc.other_chat_source = 1
            
            GlobalPresent(toController: vc)
         
        }
        
        GlobalPresent(toController: pair)
        
    }
    
    
    func presentChatController(sessionId:String,chatTitle:String)  {
        
        
        push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: sessionId, title: chatTitle, source: "个人主页"), navigationController: nil)
        
        /*
        let vc = ST_PrivateChatViewController()
        
        vc.sessionID = sessionId
        
        vc.chatTitle = chatTitle
        
        vc.source = "个人主页"
        
        GlobalPresent(toController: vc)
        
        let session = NIMSession.init(sessionId, type: NIMSessionType.P2P)
        
        NIMSDK.shared().conversationManager.markAllMessagesRead(in: session)
        
        ST_ConversationAdapter.shared.updateAllData()
        
         */
    }
}

extension ST_BTBootController:UINavigationControllerDelegate{

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
     
        navigationController.interactivePopGestureRecognizer?.isEnabled = navigationController.viewControllers.count > 1
    }
    
}


//MARK: - Global Method
/**
 最大可展示 不被释放数量
 */
fileprivate let MAX_SHOW_CONTROLLER_COUNT = 12

func GlobalPresent(toController:UIViewController,animated flag: Bool = true){
    
    GlobalPresent(toController: toController, animated: flag, completion: nil)
    
}

func GlobalPresent(toController:UIViewController,animated flag: Bool = true,completion: (() -> Void)? = nil)  {
    
    
    CURRENT_PLAYING_GROUPHEADER_VIEW?.playerStatus(isMute: true)
    
    guard var rootController = UIApplication.shared.tainMainWindow?.rootViewController else { return}
    
//    var rootController:UIViewController = rootController
    if #available(iOS 13.0, *) ,toController.modalPresentationStyle == .pageSheet {
        toController.modalPresentationStyle = .fullScreen
    }
    
    
    
    var number = 1
    
    while rootController.presentedViewController != nil {
        
        rootController = rootController.presentedViewController!
        
        number += 1
    }
    
    if number > MAX_SHOW_CONTROLLER_COUNT{
        
        print("内存 超出了")
        
        
        UIApplication.shared.tainMainWindow?.rootViewController?.dismiss(animated: false, completion: {
            
            UIApplication.shared.tainMainWindow?.rootViewController?.present(toController, animated: flag, completion: completion)
            
        })
        
    }else{
        
        print("内存 未超出")
        
        rootController.present(toController, animated: flag, completion: completion)
    }
    
    
    
}

func GlobalCustomPresent(toController:UIViewController,animated flag: Bool = true)  {
    
    
    var rootController:UIViewController = ST_BTBootController.shared
    
    while rootController.presentedViewController != nil {
        
        rootController = rootController.presentedViewController!
    }
    
    toController.modalPresentationStyle = .custom
    
    rootController.present(toController, animated: flag, completion: nil)
    
}




func GlobalToast(text:String)  {
    
    
    var rootController:UIViewController = ST_BTBootController.shared
    
    while rootController.presentedViewController != nil {
        
        rootController = rootController.presentedViewController!
    }
    
    ToastHud(text: text, view: rootController.view)
    
    
}




/**
 当前 会员状态
 */
func FETCH_MEMBER_STATUS()->ST_BTMemberStatus{
    
    guard let expiration_time = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.vip_expire ,expiration_time > 0 else { return  .normal}
    
    return CHECK_MEMBER_STATUS(expirationTime: expiration_time)
}

func CHECK_MEMBER_STATUS(expirationTime:Int)->ST_BTMemberStatus{
    
    //    当前时间 小于等于 过期时间
    if Date().timeIntervalSince1970.int <= expirationTime{
        return .subscribe
    }else{
        return .expired
    }
}


/**
 不够 发起聊天
 */
func ArrestChatLine(isVideo:Bool)->Bool {
    
    guard let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo,user.sex == .male else{
        return false
    }
    
    
    guard let attributes = ST_BTUserInfoManager.shared.additional_attributes else{
        return true
    }
    
    /// 初体验次数 &&  甜心币
    if attributes.firstImpressionCount > 0 && user.sweet_coin > 0.99{
        return false
    }
    
    
    let freeNumber = attributes.liveTalkFreeNumber
//    次数大于0  或者 甜心币大于25
    if freeNumber > 0 || user.sweet_coin >= 25{
        return false
    }
    
    return true
}



// 过期
func BTSameCityExpired()->Bool{
    
    guard let sameCityTime = ST_BTUserInfoManager.shared.current_account_info?.extra_data?.same_city_expire else { return  true}
    
    //    当前时间 小于等于 过期时间
    if Date().timeIntervalSince1970.int <= sameCityTime{
        return false
    }
    return true
}
